<?php
namespace app\common\service;


use app\common\util\Util;
use think\Db;
use think\Model;

class UserResourcesService extends BaseService
{

    /**
     * 微信端: 新增用户资源数据
     * @param $sid
     * @param $uid
     * @param $save_path
     * @param $img_name
     * @param $img_url
     * @return int
     */
    public function addUserResources($sid, $uid, $save_path, $img_name, $img_url){
        //图片保存路径
        $save_img_path = $save_path . DS . $img_name;

        //图片pathinfo
        $img_pathinfo = pathinfo($img_name);

        //存入资源表
        $resources_data = [
            'sid' => $sid,
            'uid' => $uid,
            'name' => $img_name,
            'savename' => $img_name,
            'img_url' => $img_url,
            'savepath' => $save_img_path,
            'ext' => $img_pathinfo['extension'],
            'mime' => mime_content_type($save_img_path),  //图片MIME类型
            'size' => filesize($save_img_path),  //图片大小
            'create_time' => time()
        ];

        $user_resources_id = db('user_resources')->insertGetId($resources_data);
        return $user_resources_id;
    }


    /**
     * 微信端: 输出文件流
     * @param $sid
     * @param $id
     * @return array
     */
    public function getUserResourcesStream($sid, $id){
        $info = db('user_resources')->where(['id' => $id, 'sid' => $sid, 'status' => 1])->find();
        if(!$info){
            return ['status' => 0, 'msg' => '用户资源不存在'];
        }

        if(!file_exists($info['savepath'])){
            return ['status' => 0, 'msg' => '用户资源路径不存在'];
        }

        Header('Content-type: image/jpeg');
        echo file_get_contents($info['savepath']);
    }


    /**
     * 微信端: 获取用户资源URL地址 UID=0时，为后台复用
     * @param $sid
     * @param $uid
     * @param $user_resources_id
     * @return string
     */
    public function getUserResourcesUrl($sid, $uid, $user_resources_id){
        if($uid > 0){
            return $this->domain.'/api/front/user_resources/detail?sid='.$sid.'&uid='.$uid.'&id='.$user_resources_id;

        } else {
            return $this->domain.'/api/admin/user_resources/detail?sid='.$sid.'&id='.$user_resources_id;
        }
    }
}